package com.wcgksoft.controller.insect;


import com.wcgksoft.common.util.FileHandleUtil;
import com.wcgksoft.common.util.Layui;
import com.wcgksoft.common.util.comm.StringUtils;
import com.wcgksoft.entity.GreedLand.GreedLandAdministrator;
import com.wcgksoft.entity.Plant.PlantEncyclopedias;
import com.wcgksoft.entity.insect.*;
import com.wcgksoft.entity.system.EnterpriseProject;
import com.wcgksoft.entity.system.SysUser;
import com.wcgksoft.service.GreedLand.GreedlandAdministratorService;
import com.wcgksoft.service.GreedLand.GreedlandService;
import com.wcgksoft.service.insect.*;
import com.wcgksoft.service.plant.PlantEncyclopediasService;
import net.sf.ezmorph.object.DateMorpher;
import net.sf.json.JSONObject;
import net.sf.json.util.JSONUtils;
import org.apache.shiro.SecurityUtils;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.List;


/**
 *
 * 虫情历史
 *
 */
@Controller
@RequestMapping("insect/insectHistory")
public class InsectHistoryController {


    @Autowired
    private InsectHistoryService insectHistoryService;


    @Autowired
    private InsectBadPhotoService insectBadPhotoService;

    @Autowired
    private InsectGoodPhotoService insectGoodPhotoService;

    @Autowired
    private GreedlandAdministratorService greedlandAdministratorService;

    @Autowired
    private InsectDetectionService insectDetectionService;

    @Autowired
    private GreedlandService greedlandService;

    @Autowired
    private PlantEncyclopediasService plantEncyclopediasService;

    @Autowired
    private DisposalMethodsService disposalMethodsService;

    @Autowired
    private InsectTypeService insectTypeService;

    @Autowired
    private MedicamentTypeService medicamentTypeService;


    /**
     * 查询虫情历史
     */

    @ResponseBody
    @RequestMapping(value = "findAll")
    public Layui findAll(HttpServletRequest request,
                         @RequestParam(value = "keywords",required = false)String keywords,
                         @RequestParam(value = "page", required = false) Integer page,
                         @RequestParam(value = "limit", required = false) Integer limit) {
        //SysUser sysUser = (SysUser) SecurityUtils.getSubject().getSession().getAttribute("om_user");

        EnterpriseProject enterpriseProject = (EnterpriseProject) SecurityUtils.getSubject().getSession().getAttribute("area");
        DetachedCriteria criteria = DetachedCriteria.forClass(InsectHistory.class);
        criteria.add(Restrictions.eq("areaId",enterpriseProject.getId()));
        if(StringUtils.isNotEmpty(keywords)) {
            criteria.add(Restrictions.like("types", keywords, MatchMode.ANYWHERE));
        }
        List<InsectHistory> list = insectHistoryService.findByConditions(criteria,page,limit);

        for (InsectHistory insectHistory : list) {
            DetachedCriteria criteria1 = DetachedCriteria.forClass(InsectBadPhoto.class);
            criteria1.add(Restrictions.eq("historyId",insectHistory.getId()));
            List<InsectBadPhoto> byConditions = insectBadPhotoService.findByConditions(criteria1);
            insectHistory.setInsectBadPhotos(byConditions);
        }

        for (InsectHistory insectHistory : list) {
            DetachedCriteria criteria2 = DetachedCriteria.forClass(InsectGoodPhoto.class);
            criteria2.add(Restrictions.eq("historyId",insectHistory.getId()));
            List<InsectGoodPhoto> byConditions = insectGoodPhotoService.findByConditions(criteria2);
            insectHistory.setInsectGoodPhotos(byConditions);
        }

        return Layui.data(0, "查询成功", insectHistoryService.getTotalCount(), list);
    }






    /**
     * 查询植物
     * @param page
     * @param limit
     * @param name
     * @return
     * @throws UnsupportedEncodingException
     */
    @ResponseBody
    @RequestMapping(value = "list")
    public Layui list(
            @RequestParam(value = "page", required = false) Integer page,
            @RequestParam(value = "limit", required = false) Integer limit,
            @RequestParam(value = "name", required = false) String name) throws UnsupportedEncodingException {
        SysUser sysUser = (SysUser) SecurityUtils.getSubject().getSession().getAttribute("om_user");
        EnterpriseProject enterpriseProject = (EnterpriseProject) SecurityUtils.getSubject().getSession().getAttribute("area");
        DetachedCriteria criteria = DetachedCriteria.forClass(PlantEncyclopedias.class);
        criteria.add(Restrictions.eq("enterpriseid", sysUser.getEnterprise().getId()));
        if(org.apache.commons.lang.StringUtils.isNotEmpty(name)) {
//            keyWord = new String(keyWord.getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
            criteria.add(Restrictions.like("name", name, MatchMode.ANYWHERE));
        }
        List<PlantEncyclopedias> list = plantEncyclopediasService.findByConditions(criteria, page, limit);
        return Layui.data(0, "查询成功", plantEncyclopediasService.getTotalCount(), list);
    }

    /**
     * 查找绿地
     */

    @ResponseBody
    @RequestMapping(value = "findGreen")
    public Layui findGreen() {
        EnterpriseProject enterpriseProject = (EnterpriseProject) SecurityUtils.getSubject().getSession().getAttribute("area");
        DetachedCriteria criteria = DetachedCriteria.forClass(GreedLandAdministrator.class);
        criteria.add(Restrictions.eq("areaid",enterpriseProject.getId()));
        List<GreedLandAdministrator> list = greedlandAdministratorService.findByConditions(criteria);
        return Layui.data(0, "查询成功", greedlandAdministratorService.getTotalCount(), list);
    }

    //查询虫害类型
    @ResponseBody
    @RequestMapping(value = "findInsectType")
    public Layui find() {

        DetachedCriteria criteria = DetachedCriteria.forClass(InsectType.class);

        List<InsectType> list = insectTypeService.findByConditions(criteria);
        return Layui.data(0, "查询成功", insectTypeService.getTotalCount(), list);
    }
    //查询处置方法
    @ResponseBody
    @RequestMapping(value = "findDisposalMethods")
    public Layui find2() {

        DetachedCriteria criteria = DetachedCriteria.forClass(DisposalMethods.class);

        List<DisposalMethods> list = disposalMethodsService.findByConditions(criteria);
        return Layui.data(0, "查询成功", disposalMethodsService.getTotalCount(), list);
    }


    //查询药剂类型
    @ResponseBody
    @RequestMapping(value = "findMedicamentType")
    public Layui find1() {

        DetachedCriteria criteria = DetachedCriteria.forClass(MedicamentType.class);

        List<MedicamentType> list = medicamentTypeService.findByConditions(criteria);
        return Layui.data(0, "查询成功", medicamentTypeService.getTotalCount(), list);
    }


    /**
     * 添加虫情历史
     */

    @ResponseBody
    @RequestMapping(value = "update")
    public Layui update(HttpServletRequest request,
                        @RequestParam(value = "data", required = false) String data,
                        @RequestParam(value = "file", required = false) MultipartFile[] file,
                        @RequestParam(value = "file1", required = false) MultipartFile[] file1) throws IOException {
        EnterpriseProject enterpriseProject = (EnterpriseProject) SecurityUtils.getSubject().getSession().getAttribute("area");

        SysUser sysUser = (SysUser) SecurityUtils.getSubject().getSession().getAttribute("om_user");
        JSONObject param = JSONObject.fromObject(data);
        String uname = param.getString("uname");

        if (param == null) {
            return Layui.data(1, "请求格式有误", 0, null);
        } else {
            String[] dateFormats = new String[]{"yyyy-MM-dd"};
            JSONUtils.getMorpherRegistry().registerMorpher(new DateMorpher(dateFormats));
            InsectHistory insectHistory = (InsectHistory) JSONObject.toBean(JSONObject.fromObject(data), InsectHistory.class);
            insectHistory.setUname(uname);
            insectHistory.setReleaseTime(new Date());
            insectHistory.setDepartId(sysUser.getProId());
            insectHistory.setAreaId(enterpriseProject.getId());


            insectHistoryService.saveOrUpdate(insectHistory);


            for (MultipartFile mf : file) {
                InsectBadPhoto insectBadPhoto = new InsectBadPhoto();
                if (!mf.isEmpty()) {
                    String filename = FileHandleUtil.Upset(mf);
                    insectBadPhoto.setBadPhoto("upload/picture/" + FileHandleUtil.upload(mf.getInputStream(), "upload/picture/", filename, request));
                    insectBadPhoto.setHistoryId(insectHistory.getId());
                    insectBadPhoto.setTime(new Date());
                    insectBadPhotoService.saveOrUpdate(insectBadPhoto);
                }
            }
            for (MultipartFile mf1 : file1) {
                InsectGoodPhoto insectGoodPhoto = new InsectGoodPhoto();
                if (!mf1.isEmpty()) {
                    String filename = FileHandleUtil.Upset(mf1);
                    insectGoodPhoto.setGoodPhoto("upload/picture/" + FileHandleUtil.upload(mf1.getInputStream(), "upload/picture/", filename, request));
                    insectGoodPhoto.setHistoryId(insectHistory.getId());
                    insectGoodPhoto.setTime(new Date());
                    insectGoodPhotoService.saveOrUpdate(insectGoodPhoto);
                }
            }
            return Layui.data(0, "添加成功", 1, Layui.addList(insectHistory));
        }
    }


    /**
     * 删除
     */

    @ResponseBody
    @RequestMapping(value = "delete")
    public Layui delete(@RequestParam(value = "id") Integer id) {

        InsectHistory byId = insectHistoryService.findById(id);

        DetachedCriteria criteria = DetachedCriteria.forClass(InsectBadPhoto.class);
        criteria.add(Restrictions.eq("historyId",id));
        List<InsectBadPhoto> list = insectBadPhotoService.findByConditions(criteria);
        for (InsectBadPhoto insectBadPhoto : list) {
            InsectBadPhoto badId = insectBadPhotoService.findById(insectBadPhoto.getId());
            insectBadPhotoService.delete(badId);
        }

        DetachedCriteria criteriaa = DetachedCriteria.forClass(InsectGoodPhoto.class);
        criteria.add(Restrictions.eq("historyId",id));
        List<InsectGoodPhoto> lists = insectGoodPhotoService.findByConditions(criteriaa);
        for (InsectGoodPhoto insectGoodPhoto : lists) {
            InsectGoodPhoto goodId = insectGoodPhotoService.findById(insectGoodPhoto.getId());
            insectGoodPhotoService.delete(goodId);
        }
        insectHistoryService.delete(byId);
        return Layui.data(1, "删除成功", 1, null);
    }



}
